package com.fjh.impl;

import com.fjh.dao.BookDao;
import com.fjh.dao.BookRowMapper;
import com.fjh.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class BookDaoImpl implements BookDao {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public BookDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void addBook(Book book) {
        String sql = "INSERT INTO book (name, author, publisher, price) VALUES (?, ?, ?, ?)";
        jdbcTemplate.update(sql, book.getName(), book.getAuthor(), book.getPublisher(), book.getPrice());
    }

    @Override
    public Book getBookById(int id) {
        String sql = "SELECT * FROM book WHERE id=?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BookRowMapper());
    }

    @Override
    public void updateBook(Book book) {
        String sql = "UPDATE book SET name=?, author=?, publisher=?, price=? WHERE id=?";
        jdbcTemplate.update(sql, book.getName(), book.getAuthor(), book.getPublisher(), book.getPrice(), book.getId());
    }

    @Override
    public void deleteBook(int id) {
        String sql = "DELETE FROM book WHERE id=?";
        jdbcTemplate.update(sql, id);
    }

    private static class BookRowMapper implements RowMapper<Book> {
        @Override
        public Book mapRow(ResultSet resultSet, int i) throws SQLException {
            Book book = new Book();
            book.setId(resultSet.getInt("id"));
            book.setName(resultSet.getString("name"));
            book.setAuthor(resultSet.getString("author"));
            book.setPublisher(resultSet.getString("publisher"));
            book.setPrice(resultSet.getDouble("price"));
            return book;
        }
    }
}